package com.example.casper.Experiment2024.data;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataBank {
private final Context context;
private final String data_file_book ="Book.data";
private final String data_file_record ="record.data";
    public DataBank(Context context) {
        this.context=context;
    }
    public Context getContext() {
        return context;
    }
    public List<Book> readBooks() {
        List<Book> book=new ArrayList<>();
        try {
            FileInputStream fileIn= context.openFileInput(data_file_book);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            book = (List<Book>) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException | ClassNotFoundException ignored) {
        }
        return book;
    }
    public void saveBooks(List<Book> bookList) {
        FileOutputStream fileout;
        try {
            fileout = context.openFileOutput(data_file_book, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileout);
            out.writeObject(bookList);
            out.close();
            fileout.close();
        } catch (IOException ignored) {
        }
    }

    public List<Records> readRecords() {
        List<Records> records=new ArrayList<>();
        try {
            FileInputStream fileIn= context.openFileInput(data_file_record);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            records = (List<Records>) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException | ClassNotFoundException ignored) {
        }
        return records;
    }
    public void saveRecords(List<Records> recordsList) {
        FileOutputStream fileout;
        try {
            fileout = context.openFileOutput(data_file_record, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileout);
            out.writeObject(recordsList);
            out.close();
            fileout.close();
        } catch (IOException ignored) {
        }
    }
}
